import axios from 'axios'

const API_BASE_URL = process.env.VUE_APP_API_BASE_URL || 'http://localhost:8891/api'

// 创建axios实例
const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器，添加Authorization header
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 用户管理API
export const userAPI = {
  // 获取用户列表
  getUserList() {
    return api.get('/users')
  },

  // 创建用户
  createUser(userData) {
    return api.post('/users', userData)
  },

  // 获取单个用户信息
  getUser(userId) {
    return api.get(`/users/${userId}`)
  },

  // 更新用户信息
  updateUser(userId, userData) {
    return api.put(`/users/${userId}`, userData)
  },

  // 删除用户
  deleteUser(userId) {
    return api.delete(`/users/${userId}`)
  },

  // 重置用户密码
  resetUserPassword(userId, newPassword) {
    return api.post(`/users/${userId}/reset-password`, {
      new_password: newPassword
    })
  }
}

export default userAPI